package com.ipay.wechat.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.ipay.utils.Constant;
import com.ipay.utils.StringUtil;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.dao.MerchantInfoDao;
import com.ipay.wechat.pojo.MerchantInfoEntity;
import com.ipay.wechat.service.MerchantInfoService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ipay.entity.BizSequenceType;
import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.service.impl.DefaultSequenceManager;
import com.ipay.utils.R;
import com.ipay.utils.RandomStringUtils;
import com.ipay.wechat.pojo.Cashiers;
import com.ipay.wechat.pojo.MerchantInfo;
import com.ipay.wechat.pojo.WechatLogin;
import com.ipay.wechat.service.ApplyService;
import com.ipay.wechat.service.CashiersService;
import com.ipay.wechat.service.LoginService;
import com.ipay.wechat.util.MapUtil;
import com.ipay.wechat.util.UploadUtil;

import net.sf.json.JSONObject;

@Transactional
@Controller
public class ApplyController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ApplyService applyService;
    @Autowired
    private CashiersService cashiersService;
    @Autowired
    private JedisExecutor jedies;
    @Autowired
    private LoginService loginService;
    @Autowired
    private Wechat wechat;
    @Autowired
    private MerchantInfoService merchantInfoService;
    /**
     * 商家入驻入口
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("/auth/isApply")
    public ModelAndView isApply(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        //openid = "oejR50ugUxEvsvfyzR5dHfZv_899";
        //根据openid查询用户登录表  如果有数据根据登录表手机号码查询 收款员表 判断用户类型是否为管理员或收款员
        WechatLogin login = loginService.findWechatLoginByOpenid(openid);
        if(login != null){
        	String mobile = login.getMobilephone();
        	Cashiers cashiers = cashiersService.findCashierByMobile(mobile, Constant.ActivateState.T_DELETED.getValue());
        	if(cashiers != null && cashiers.getRole() == 1){//1表示管理员
        		request.getSession().setAttribute("status", 1); //已审核
                return new ModelAndView("apply/applysuccess1.jsp");
        	}
        }
        MerchantInfo info = applyService.getInfoByOpenid(openid);
        if (info == null) {   //该微信账户未入网
            return new ModelAndView("apply/applyCompany.jsp");//商户入驻  第一步
        } else {
            if (StringUtil.isNotEmpty(info.getStatus()) && info.getStatus() == 1) {//已审核
                map.put("status", 1);//已审核
            } else {
                map.put("status", 0);//未审核
                if (StringUtil.isNotEmpty(info.getPresentNub()) && info.getPresentNub() == 1) {
                    return new ModelAndView("apply/applyLegalPerson.jsp");//商户入驻  第二步
                } else if (StringUtil.isNotEmpty(info.getPresentNub()) && info.getPresentNub() == 2) {
                    return new ModelAndView("apply/applySettlingAccount.jsp");//商户入驻  第三步
                }
            }
            return new ModelAndView("apply/applysuccess1.jsp");
        }
    }

    /**
     * 根据手机号码查询是否注册商户或收款员
     * mobile   String 手机
     *
     * @param request HttpServletRequest
     *                response HttpServletResponse
     */
    @RequestMapping("/auth/checkMobile")
    @ResponseBody
    public R checkMobile(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        //根据手机号码查询商户表中是否有未删除数据
        MerchantInfo mInfo = applyService.querryMerchantInfoByMobile(mobile);
        if (mInfo != null) {
            return R.error("当前手机号已注册商户,请更换手机号码注册");
        }
        //根据手机号码查询收款员中是否有未删除数据
		Cashiers cash = cashiersService.findCashierByMobile(mobile,Constant.ActivateState.T_DELETED.getValue());
		if(cash != null){
			return R.error("当前手机号已注册收款员,请更换手机号码注册");
		}
		return R.ok();
	}

    /**
     * 上一步操作处理
     */
    @RequestMapping("/auth/submitUpStep")
    public ModelAndView submitUpStep(HttpServletRequest request, @RequestParam("presentNub") String presentNub, ModelMap modelMap) {
        String openid = (String) request.getSession().getAttribute("openid");
        //根据openid 查询商户表是否有未删除数据
        MerchantInfoEntity merInfo = merchantInfoService.querryInfoByMInfoOpenid(openid);
        if (merInfo == null) {   //该微信账户未入网
            return new ModelAndView("apply/applyCompany.jsp");//商户入驻  第一步
        } else {
            if (StringUtil.isNotEmpty(merInfo.getStatus()) && merInfo.getStatus() == 1) {//已审核
                modelMap.put("status", 1);//已审核
            } else {
                modelMap.put("status", 0);//未审核
                if (StringUtil.isNotEmpty(merInfo.getPresentNub()) && merInfo.getPresentNub() != 3) {
                    if(StringUtil.isNotEmpty(presentNub)&&presentNub.equals("1")){
                        modelMap.put("merchantInfo", merInfo);
                        modelMap.put("applyStart", "merInfoOne");
                        return new ModelAndView("apply/applyCompany.jsp");//商户入驻  第一步
                    }else if(StringUtil.isNotEmpty(presentNub)&&presentNub.equals("2")){
                        modelMap.put("merchantInfo", merInfo);
                        modelMap.put("applyStart", "merInfoTwo");
                        return new ModelAndView("apply/applyLegalPerson.jsp");//商户入驻  第二步
                    }else{
                        modelMap.put("message", "数据错误");
                        return applyError();
                    }
                }
            }
            return new ModelAndView("apply/applysuccess1.jsp");
        }
    }

    /**
     * 商户入驻  第一步
     *
     * @param s_name           企业名称
     * @param shopAbbreviation 企业简称
     * @param s_addr           企业地址
     * @param telephone        客服电话
     * @param username         联系人姓名
     * @param mobile           联系人电话
     * @param email            联系人邮箱
     * @param request
     * @return
     */
    @RequestMapping(value = "/auth/submitCompany", method = RequestMethod.POST)
    public ModelAndView submitCompany(@RequestParam String s_name,@RequestParam String applyStart,
                                      @RequestParam String shopAbbreviation,
                                      @RequestParam String s_addr,
                                      @RequestParam String telephone,
                                      @RequestParam String username,
                                      @RequestParam String mobile,
                                      @RequestParam String email,
                                      HttpServletRequest request, ModelMap modelMap) {
        String openid = (String) request.getSession().getAttribute("openid");
        //根据openid 查询商户表是否有未删除数据    只查询商户表
        MerchantInfoEntity merInfo = merchantInfoService.querryInfoByMInfoOpenid(openid);
        //根据手机号码查询商户表中是否有未删除数据
        String merchantNo;
        if(StringUtil.isEmpty(applyStart)||(!applyStart.equals("merInfoOne"))) {
            if (merInfo != null && StringUtil.isNotEmpty(merInfo.getMerchantNo())) {
                modelMap.put("message", "当前微信已注册商户，请联系管理员");
                return applyError();
            }
            MerchantInfo mInfo = applyService.querryMerchantInfoByMobile(mobile);
            if (mInfo != null && StringUtil.isNotEmpty(mInfo.getMerchantNo())) {
                modelMap.put("message", "当前手机号已注册商户，请联系管理员");
                return applyError();
            }
            //根据手机号码查询收款员表中是否有未删除数据
            Cashiers cashiers = cashiersService.findCashierByMobile(mobile,Constant.ActivateState.T_DELETED.getValue());
            if (cashiers != null && StringUtil.isNotEmpty(cashiers.getMerchantId())) {
                modelMap.put("message", "当前手机号已注册收款员，请联系管理员");
                return applyError();
            }
            merchantNo = DefaultSequenceManager.get().next(BizSequenceType.MERCHANTNO);//商户号
        }else{
            if (merInfo == null || StringUtil.isEmpty(merInfo.getMerchantNo())) {
                modelMap.put("message", "操作数据获取失败");
                return applyError();
            }
            merchantNo = merInfo.getMerchantNo();//商户号
        }
        JSONObject jsonInfo = new JSONObject();
        jsonInfo.put("s_name", s_name);
        jsonInfo.put("shopAbbreviation", shopAbbreviation);
        jsonInfo.put("s_addr", s_addr);
        jsonInfo.put("telephone", telephone);
        jsonInfo.put("username", username);
        jsonInfo.put("mobile", mobile);
        jsonInfo.put("email", email);

        jsonInfo.put("openid", openid);
        jsonInfo.put("merchantNo", merchantNo);
        HashMap<String, String> map = MapUtil.toHashMap(jsonInfo);
        logger.info("====商户入驻------第一步===：" + map.toString());
        try {
            if(StringUtil.isNotEmpty(applyStart)&&applyStart.equals("merInfoOne")) {
                applyService.saUpdateCompany(map);
                if(StringUtil.isNotEmpty(merInfo.getLegalName())){
                    modelMap.put("merchantInfo", merInfo);
                    modelMap.put("applyStart", "merInfoTwo");
                }
            }else{
                applyService.saveCompany(map);
            }
            return new ModelAndView("apply/applyLegalPerson.jsp");
        } catch (Exception e) {
            logger.error("保存商户注册信息错误", e);
            modelMap.put("message", "系统繁忙，请稍候重试！");
            return applyError();
        }
    }

    /**
     * 商户入驻 第二步
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/auth/submitLegalPerson", method = RequestMethod.POST)
    public ModelAndView submitLegalPerson(@RequestParam String applyStart,
            @RequestParam String legalName,@RequestParam String idCard,
            MultipartFile positive,MultipartFile opposite,
            MultipartFile businessLicense,MultipartFile bankLicense,
            HttpServletRequest request, ModelMap modelMap) {
       String openid = (String) request.getSession().getAttribute("openid");
        //根据openid 查询商户表是否有未删除数据    只查询商户表
        MerchantInfoEntity merInfo = merchantInfoService.querryInfoByMInfoOpenid(openid);
        if (merInfo == null || StringUtil.isEmpty(merInfo.getMerchantNo())) {
            return new ModelAndView("apply/applyCompany.jsp");//商户入驻  第一步
        } else {
            if(StringUtil.isEmpty(applyStart)||(!applyStart.equals("merInfoTwo"))) {
                if (StringUtil.isNotEmpty(merInfo.getStatus()) && merInfo.getStatus() == 0) {
                    if (StringUtil.isNotEmpty(merInfo.getPresentNub()) && merInfo.getPresentNub() == 2) {  //第二步已操作  可以直接进入第三步
                        return new ModelAndView("apply/applySettlingAccount.jsp");
                    } else if (StringUtil.isNotEmpty(merInfo.getPresentNub()) && merInfo.getPresentNub() == 3) { //第三步操作  可以直接进入申请成功页面
                        modelMap.put("status", 0);//未审核
                        return new ModelAndView("apply/applysuccess1.jsp");
                    }
                } else if (StringUtil.isNotEmpty(merInfo.getStatus()) && merInfo.getStatus() == 1) {
                    modelMap.put("status", 1);//已审核
                    return new ModelAndView("apply/applysuccess1.jsp");
                } else {
                    logger.info("=====商户状态错误==:" + merInfo);
                    modelMap.put("message", "商户状态错误");
                    return applyError();
                }
            }
        }
        JSONObject jsonInfo = new JSONObject();
        jsonInfo.put("legalName", legalName);//法人姓名==
        jsonInfo.put("idCard", idCard);//法人身份证号码==
        jsonInfo.put("opposite", "");
        jsonInfo.put("positive", "");
        jsonInfo.put("businessLicense", "");
        jsonInfo.put("bankLicense", "");
        //可以使用FileUtils来保存文件，这里不再列出代码
        //方法会自动关闭IO流
        String merchantNo = merInfo.getMerchantNo();//商户号
        String filePath = wechat.getUploadImgPath() + "/" + merchantNo + "/" + "merchantInfo" + "/";
        File savefile = new File(filePath);
        if (!savefile.exists()) { // 如果不存在就创建一个
            try {
                savefile.mkdirs();
            } catch (SecurityException e) {
                logger.info("创建目录异常：", e);
            }
        }
        String imgPath = "/" + merchantNo + "/" + "merchantInfo" + "/";
        logger.info("======imgPath:" + imgPath+"   =filePath:"+filePath);
        try {
            if (positive != null && positive.getSize() > 0) {
                logger.info("====身份证正面: ====文件长度: 文件类型: 【" + positive.getContentType() + "】文件名称: 文件原名: 【" + positive.getOriginalFilename() + "】");
                inputStreamToFile(jsonInfo, positive, filePath, imgPath, "positive");
                logger.info("======身份证正面: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("positive"));
            }
            if (opposite != null && opposite.getSize() > 0) {
                logger.info("======身份证反面: 文件原名: " + opposite.getOriginalFilename());
                inputStreamToFile(jsonInfo, opposite, filePath, imgPath, "opposite");
                logger.info("======身份证反面: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("opposite"));
            }
            if (businessLicense != null && businessLicense.getSize() > 0) {
                logger.info("======营业执照:文件原名: " + businessLicense.getOriginalFilename());
                inputStreamToFile(jsonInfo, businessLicense, filePath, imgPath, "businessLicense");
                logger.info("======营业执照: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("businessLicense"));
            }
            if (bankLicense != null && bankLicense.getSize() > 0) {
                logger.info("======银行开户许可证:文件原名: " + bankLicense.getOriginalFilename());
                inputStreamToFile(jsonInfo, bankLicense, filePath, imgPath, "bankLicense");
                logger.info("======银行开户许可证: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("bankLicense"));
            }
        } catch (IOException e1) {
            logger.error("文件保存出错 ", e1);
            request.getSession().setAttribute("message", "证件图片上传失败！");
            return applyError();
        }
        jsonInfo.put("openid", openid);
        jsonInfo.put("merchantNo", merchantNo);
        HashMap<String, String> map = MapUtil.toHashMap(jsonInfo);
        logger.info("map===" + map.toString());
        try {
            applyService.saUpdateLegalPerson(map);
            return new ModelAndView("apply/applySettlingAccount.jsp");
        } catch (Exception e) {
            logger.error("保存商户注册信息错误", e);
            modelMap.put("message", "系统繁忙，请稍候重试！");
            return applyError();
        }
    }

    /**
     * 商户入驻  第三步
     *
     * @param outer
     * @param request
     * @return
     */
    @RequestMapping(value = "/auth/submitSettlingAccount", method = RequestMethod.POST)
    public ModelAndView submitSettlingAccount(
            @RequestParam String bankUser,@RequestParam String bankName,@RequestParam String bankCard,
            MultipartFile outer,MultipartFile settlementBook,
            MultipartFile settleUserPositive,MultipartFile settleUserOpposite,
            MultipartFile settleBankPositive,MultipartFile settleBankOpposite,
            MultipartFile sealCard,HttpServletRequest request, ModelMap modelMap) {
       String openid = (String) request.getSession().getAttribute("openid");
        //根据openid 查询商户表是否有未删除数据    只查询商户表
        MerchantInfoEntity merInfo = merchantInfoService.querryInfoByMInfoOpenid(openid);
        if (merInfo == null || StringUtil.isEmpty(merInfo.getMerchantNo())) {
            return new ModelAndView("apply/applyCompany.jsp");//商户入驻  第一步
        } else {
            if (StringUtil.isNotEmpty(merInfo.getStatus()) && merInfo.getStatus() == 0) {//未审核
                if (StringUtil.isNotEmpty(merInfo.getPresentNub()) && merInfo.getPresentNub() == 1) {  //第一步已操作  可以直接进入第二步
                    return new ModelAndView("apply/applyLegalPerson.jsp");
                } else if (StringUtil.isNotEmpty(merInfo.getPresentNub()) && merInfo.getPresentNub() == 3) { //第三步操作  可以直接进入申请成功页面
                    modelMap.put("status", 0);//未审核
                    return new ModelAndView("apply/applysuccess1.jsp");
                }
            } else if (StringUtil.isNotEmpty(merInfo.getStatus()) && merInfo.getStatus() == 1) {//已审核
                modelMap.put("status", 1);//已审核
                return new ModelAndView("apply/applysuccess1.jsp");
            } else {
                logger.info("=====商户状态错误==:" + merInfo);
                modelMap.put("message", "商户状态错误");
                return applyError();
            }
        }
        JSONObject jsonInfo = new JSONObject();
        jsonInfo.put("bankUser", bankUser);
        jsonInfo.put("bankName", bankName);
        jsonInfo.put("bankCard", bankCard);
        //可以使用FileUtils来保存文件，这里不再列出代码
        //方法会自动关闭IO流
        String merchantNo = merInfo.getMerchantNo();//商户号
        String filePath = wechat.getUploadImgPath() + "/" + merchantNo + "/" + "merchantInfo" + "/";
        File savefile = new File(filePath);
        if (!savefile.exists()) {// 如果不存在就创建一个
            try {
                savefile.mkdirs();
            } catch (SecurityException e) {
                logger.info("创建目录异常：", e);
            }
        }
        String imgPath = "/" + merchantNo + "/" + "merchantInfo" + "/";
        logger.info("===filePath:" + filePath+"  imgPath:"+imgPath);
        try {
            if (outer != null && outer.getSize() > 0) {
                logger.info("===================店铺室外: 文件原名: " + outer.getOriginalFilename());
                inputStreamToFile(jsonInfo, outer, filePath, imgPath, "outer");
                logger.info("===================店铺室外: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("outer"));
            }
            if (settlementBook != null && settlementBook.getSize() > 0) {
                logger.info("===================结算授权书:文件原名: " + settlementBook.getOriginalFilename());
                inputStreamToFile(jsonInfo, settlementBook, filePath, imgPath, "settlementBook");
                logger.info("===================结算授权书: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("settlementBook"));
            }
            if (settleUserPositive != null && settleUserPositive.getSize() > 0) {
                logger.info("===================结算人身份证正面:文件原名: " + settleUserPositive.getOriginalFilename());
                inputStreamToFile(jsonInfo, settleUserPositive, filePath, imgPath, "settleUserPositive");
                logger.info("===================结算人身份证正面: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("settleUserPositive"));
            }
            if (settleUserOpposite != null && settleUserOpposite.getSize() > 0) {
                logger.info("===================结算人身份证反面:文件原名: " + settleUserOpposite.getOriginalFilename());
                inputStreamToFile(jsonInfo, settleUserOpposite, filePath, imgPath, "settleUserOpposite");
                logger.info("===================结算人身份证反面: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("settleUserOpposite"));
            }
            if (settleBankPositive != null && settleBankPositive.getSize() > 0) {
                logger.info("===================结算人银行卡正面:文件原名: " + settleBankPositive.getOriginalFilename());
                inputStreamToFile(jsonInfo, settleBankPositive, filePath, imgPath, "settleBankPositive");
                logger.info("===================结算人银行卡正面: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("settleUserOpposite"));
            }
            if (settleBankOpposite != null && settleBankOpposite.getSize() > 0) {
                logger.info("===================结算人银行卡反面:文件原名: " + settleBankOpposite.getOriginalFilename());
                inputStreamToFile(jsonInfo, settleBankOpposite, filePath, imgPath, "settleBankOpposite");
                logger.info("===================结算人银行卡正面: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("settleBankOpposite"));
            }
            if (sealCard != null && sealCard.getSize() > 0) {
                logger.info("==========账户申请书或印鉴卡:文件原名: " + sealCard.getOriginalFilename() + "============" + sealCard.getOriginalFilename().lastIndexOf("."));
                inputStreamToFile(jsonInfo, sealCard, filePath, imgPath, "sealCard");
                logger.info("==========账户申请书或印鉴卡: 文件原名: " + jsonInfo.size() + "  =  " + jsonInfo.get("sealCard"));
            }
        } catch (IOException e1) {
            logger.error("文件保存出错 ", e1);
            request.getSession().setAttribute("message", "证件图片上传失败！");
            return applyError();
        }
        jsonInfo.put("openid", openid);
        jsonInfo.put("merchantNo", merchantNo);
        jsonInfo.put("mobile", merInfo.getMobilephone());
        HashMap<String, String> map = MapUtil.toHashMap(jsonInfo);
        logger.info("map===" + map.toString());
        try {
            applyService.saUpdateSettlingAccount(map);
            modelMap.put("status", 0);
            return new ModelAndView("apply/applysuccess1.jsp");
        } catch (Exception e) {
            logger.error("保存商户注册信息错误", e);
            request.getSession().setAttribute("message", "系统繁忙，请稍候重试！");
            return applyError();
        }
    }

    /**
     * 图片上传优化处理
     *
     * @param jsonInfo
     * @param objectFile
     * @param filePath
     * @param imgPath
     * @param key
     * @throws IOException
     */
    private void inputStreamToFile(JSONObject jsonInfo, MultipartFile objectFile, String filePath, String imgPath, String key) throws IOException {
        logger.info("=====:文件原名: " + objectFile.getOriginalFilename() + "=========" + objectFile.getOriginalFilename().lastIndexOf("."));
        String prefix = objectFile.getOriginalFilename().substring(objectFile.getOriginalFilename().lastIndexOf("."));
        logger.info("==========" + prefix);
        String realPathSealCard = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
        FileUtils.copyInputStreamToFile(objectFile.getInputStream(), new File(filePath, realPathSealCard));
        jsonInfo.put(key, imgPath + realPathSealCard);
    }

    /**
     * 商户入驻
     *
     * @param username
     * @param mobile
     * @param s_name
     * @param s_addr
     * @param positive
     * @param opposite
     * @param outer
     * @param inner
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/submitapp")
    public ModelAndView submitapp(@RequestParam String s_name,
                                  @RequestParam String shopAbbreviation,
                                  @RequestParam String s_addr,
                                  @RequestParam String telephone,
                                  @RequestParam String username,
                                  @RequestParam String mobile,
                                  @RequestParam String email,
                                  @RequestParam String legalName,
                                  @RequestParam String idCard,
                                  @RequestParam String bankUser,
                                  @RequestParam String bankName,
                                  @RequestParam String bankCard,
                                  MultipartFile positive,
                                  MultipartFile opposite,
                                  MultipartFile outer,
                                  MultipartFile inner,
                                  MultipartFile doorHead,
                                  MultipartFile businessLicense,
                                  MultipartFile bankLicense,
                                  MultipartFile settlementBook,
                                  MultipartFile settleUserPositive,
                                  MultipartFile settleUserOpposite,
                                  MultipartFile settleBankPositive,
                                  MultipartFile settleBankOpposite,
                                  MultipartFile sealCard,
                                  HttpServletRequest request) {
        String openid = (String) request.getSession().getAttribute("openid");
        //根据手机号码查询商户表中是否有未删除数据
        MerchantInfo mInfo = applyService.querryMerchantInfoByMobile(mobile);
        if (mInfo != null) {
            request.getSession().setAttribute("message", "当前手机号已注册商户，请联系管理员");
            return applyError();
        }
        //根据手机号码查询收款员表中是否有未删除数据
        Cashiers cashiers = cashiersService.findCashierByMobile(mobile,Constant.ActivateState.T_DELETED.getValue());
        if (cashiers != null) {
            request.getSession().setAttribute("message", "当前手机号已注册收款员，请联系管理员");
            return applyError();
        }
        //根据openid 查询商户表是否有未删除数据
        MerchantInfo merInfo = applyService.querryInfoByOpenid(openid);
        if (merInfo != null) {
            request.getSession().setAttribute("message", "当前微信已注册商户，请联系管理员");
            return applyError();
        }
        JSONObject jsonInfo = new JSONObject();
        jsonInfo.put("s_name", s_name);
        jsonInfo.put("shopAbbreviation", shopAbbreviation);
        jsonInfo.put("s_addr", s_addr);
        jsonInfo.put("telephone", telephone);

        jsonInfo.put("username", username);
        jsonInfo.put("mobile", mobile);
        jsonInfo.put("email", email);

        jsonInfo.put("legalName", legalName);
        jsonInfo.put("idCard", idCard);
        jsonInfo.put("bankUser", bankUser);
        jsonInfo.put("bankName", bankName);
        jsonInfo.put("bankCard", bankCard);

        //可以使用FileUtils来保存文件，这里不再列出代码

        //方法会自动关闭IO流
        String realPathpositive = "1";//法人身份证正面
        String realPathopposite = "2";//法人身份证反面
        String realPathouter = "3";//商户门头照
        String realPathinner = "4";//商户内景照

        String realPathDoorHead = "5";//商户门头照2
        String realPathBusLicense = "6";//营业执照
        String realPathBankLicense = "7";//银行开户许可证
        String realPathSettleBook = "8";//结算授权书
        String realPathUserPositive = "9";//结算人身份证正面
        String realPathUserOppostie = "10";//结算人身份证反面
        String realPathBankPositive = "11";//结算人银行卡正面
        String realPathBankOpposite = "12";//结算人银行卡反面
        String realPathSealCard = "13";//账户申请书或印鉴卡

        String filePath = "";
        String merchantNo = DefaultSequenceManager.get().next(BizSequenceType.MERCHANTNO);//商户号
        filePath = wechat.getUploadImgPath() + "/" + merchantNo + "/" + "merchantInfo" + "/";
        logger.info("==========" + filePath);
        File savefile = new File(filePath);
        if (!savefile.exists()) {// 如果不存在就创建一个
            try {
                savefile.mkdirs();
            } catch (SecurityException e) {
                logger.info("创建目录异常：", e);
            }
        }
        try {
            if (positive != null && positive.getSize() > 0) {
                logger.info("身份证正面: ");
                logger.info("文件长度: 文件类型: " + positive.getContentType());
                logger.info("文件名称: 文件原名: " + positive.getOriginalFilename());
                logger.info("========================================");
                String prefix = positive.getOriginalFilename().substring(positive.getOriginalFilename().lastIndexOf("."));
                logger.info("文件后缀名" + prefix);
                realPathpositive = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(positive.getInputStream(), new File(filePath, realPathpositive));
            }
            if (opposite != null && opposite.getSize() > 0) {
                logger.info("身份证反面: 文件原名: " + opposite.getOriginalFilename());
                String prefix = opposite.getOriginalFilename().substring(opposite.getOriginalFilename().lastIndexOf("."));
                realPathopposite = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(opposite.getInputStream(), new File(filePath, realPathopposite));
            }
            if (outer != null && outer.getSize() > 0) {
                logger.info("店铺室外: 文件原名: " + outer.getOriginalFilename());
                logger.info("========================================");
                String prefix = outer.getOriginalFilename().substring(outer.getOriginalFilename().lastIndexOf("."));
                realPathouter = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(outer.getInputStream(), new File(filePath, realPathouter));
            }
            if (inner != null && inner.getSize() > 0) {
                logger.info("店铺室内:文件原名: " + inner.getOriginalFilename());
                logger.info("========================================");
                String prefix = inner.getOriginalFilename().substring(inner.getOriginalFilename().lastIndexOf("."));
                realPathinner = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(inner.getInputStream(), new File(filePath, realPathinner));
            }

            if (doorHead != null && doorHead.getSize() > 0) {
                logger.info("店铺室外2:文件原名: " + doorHead.getOriginalFilename());
                logger.info("========================================");
                String prefix = doorHead.getOriginalFilename().substring(doorHead.getOriginalFilename().lastIndexOf("."));
                realPathDoorHead = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(doorHead.getInputStream(), new File(filePath, realPathinner));
            }
            if (businessLicense != null && businessLicense.getSize() > 0) {
                logger.info("营业执照:文件原名: " + businessLicense.getOriginalFilename());
                logger.info("========================================");
                String prefix = businessLicense.getOriginalFilename().substring(businessLicense.getOriginalFilename().lastIndexOf("."));
                realPathBusLicense = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(businessLicense.getInputStream(), new File(filePath, realPathBusLicense));
            }
            if (bankLicense != null && bankLicense.getSize() > 0) {
                logger.info("银行开户许可证:文件原名: " + bankLicense.getOriginalFilename());
                logger.info("========================================");
                String prefix = bankLicense.getOriginalFilename().substring(bankLicense.getOriginalFilename().lastIndexOf("."));
                realPathBankLicense = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(bankLicense.getInputStream(), new File(filePath, realPathBankLicense));
            }
            if (settlementBook != null && settlementBook.getSize() > 0) {
                logger.info("结算授权书:文件原名: " + settlementBook.getOriginalFilename());
                logger.info("========================================");
                String prefix = settlementBook.getOriginalFilename().substring(settlementBook.getOriginalFilename().lastIndexOf("."));
                realPathSettleBook = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(settlementBook.getInputStream(), new File(filePath, realPathSettleBook));
            }
            if (settleUserPositive != null && settleUserPositive.getSize() > 0) {
                logger.info("结算人身份证正面:文件原名: " + settleUserPositive.getOriginalFilename());
                logger.info("========================================");
                String prefix = settleUserPositive.getOriginalFilename().substring(settleUserPositive.getOriginalFilename().lastIndexOf("."));
                realPathUserPositive = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(settleUserPositive.getInputStream(), new File(filePath, realPathUserPositive));
            }
            if (settleUserOpposite != null && settleUserOpposite.getSize() > 0) {
                logger.info("结算人身份证反面:文件原名: " + settleUserOpposite.getOriginalFilename());
                logger.info("========================================");
                String prefix = settleUserOpposite.getOriginalFilename().substring(settleUserOpposite.getOriginalFilename().lastIndexOf("."));
                realPathUserOppostie = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(settleUserOpposite.getInputStream(), new File(filePath, realPathUserOppostie));
            }
            if (settleBankPositive != null && settleBankPositive.getSize() > 0) {
                logger.info("结算人银行卡正面:文件原名: " + settleBankPositive.getOriginalFilename());
                logger.info("========================================");
                String prefix = settleBankPositive.getOriginalFilename().substring(settleBankPositive.getOriginalFilename().lastIndexOf("."));
                realPathBankPositive = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(settleBankPositive.getInputStream(), new File(filePath, realPathBankPositive));
            }
            if (settleBankOpposite != null && settleBankOpposite.getSize() > 0) {
                logger.info("结算人银行卡反面:文件原名: " + settleBankOpposite.getOriginalFilename());
                logger.info("========================================");
                String prefix = settleBankOpposite.getOriginalFilename().substring(settleBankOpposite.getOriginalFilename().lastIndexOf("."));
                realPathBankOpposite = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(settleBankOpposite.getInputStream(), new File(filePath, realPathBankOpposite));
            }
            if (sealCard != null && sealCard.getSize() > 0) {
                logger.info("账户申请书或印鉴卡:文件原名: " + sealCard.getOriginalFilename());
                logger.info("========================================" + sealCard.getOriginalFilename().lastIndexOf("."));
                String prefix = sealCard.getOriginalFilename().substring(sealCard.getOriginalFilename().lastIndexOf("."));
                logger.info("========================================" + prefix);
                realPathSealCard = RandomStringUtils.randomNumeric(8) + prefix;//随机生成一个30位字母加数字的文件名
                FileUtils.copyInputStreamToFile(sealCard.getInputStream(), new File(filePath, realPathSealCard));
            }
        } catch (IOException e1) {
            logger.error("文件保存出错 ", e1);
            request.getSession().setAttribute("message", "证件图片上传失败！");
            return applyError();
        }
        String imgPath = "/" + merchantNo + "/" + "merchantInfo" + "/";
        logger.info("imgPath========================================" + imgPath);
        jsonInfo.put("positive", imgPath + realPathpositive);
        jsonInfo.put("opposite", imgPath + realPathopposite);
        jsonInfo.put("outer", imgPath + realPathouter);
        jsonInfo.put("inner", imgPath + realPathinner);
        jsonInfo.put("doorHead", imgPath + realPathDoorHead);
        jsonInfo.put("businessLicense", imgPath + realPathBusLicense);
        jsonInfo.put("bankLicense", imgPath + realPathBankLicense);
        jsonInfo.put("settlementBook", imgPath + realPathSettleBook);
        jsonInfo.put("settleUserPositive", imgPath + realPathUserPositive);
        jsonInfo.put("settleUserOpposite", imgPath + realPathUserOppostie);
        jsonInfo.put("settleBankPositive", imgPath + realPathBankPositive);
        jsonInfo.put("settleBankOpposite", imgPath + realPathBankOpposite);
        jsonInfo.put("sealCard", imgPath + realPathSealCard);

        jsonInfo.put("openid", openid);
        jsonInfo.put("merchantNo", merchantNo);

        HashMap<String, String> map = MapUtil.toHashMap(jsonInfo);
        logger.info("map===" + map.toString());
        try {
            applyService.save(map);
            return applySuccess();
        } catch (Exception e) {
            logger.error("保存商户注册信息错误", e);
            request.getSession().setAttribute("message", "系统繁忙，请稍候重试！");
            return applyError();
        }
    }


    public static String getRandomString(int length) {
        //String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String str = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    @RequestMapping("/applySuccess")
    public ModelAndView applySuccess() {
        return new ModelAndView("applysuccess.jsp");
    }

    @RequestMapping("/applyError")
    public ModelAndView applyError() {
        //return new ModelAndView("applyerror.jsp");//---之前的
        return new ModelAndView("apply/applyerror.jsp");
    }

    /**
     * 可能是废弃的  待验证
     *
     * @param info
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/submit")
    public R submit(@RequestParam String info, HttpServletRequest request) {
        String openid = (String) request.getSession().getAttribute("openid");
        String access_token = jedies.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WECHAT_TOKEN, "access_token");
        info = info.replace("&quot;", "\"");
        JSONObject jsonInfo = JSONObject.fromObject(info);
        String positiveImg = UploadUtil.downloadMedia(jsonInfo.getString("positive"), request, access_token, jsonInfo.getString("mobile"));
        String oppsiteImg = UploadUtil.downloadMedia(jsonInfo.getString("opposite"), request, access_token, jsonInfo.getString("mobile"));
        String outerImg = UploadUtil.downloadMedia(jsonInfo.getString("outer"), request, access_token, jsonInfo.getString("mobile"));
        String innerImg = UploadUtil.downloadMedia(jsonInfo.getString("inner"), request, access_token, jsonInfo.getString("mobile"));
        jsonInfo.put("positive", wechat.getBaseUrl() + positiveImg.subSequence(positiveImg.indexOf("webapps") + 7, positiveImg.length()));
        jsonInfo.put("opposite", wechat.getBaseUrl() + oppsiteImg.subSequence(oppsiteImg.indexOf("webapps") + 7, oppsiteImg.length()));
        jsonInfo.put("outer", wechat.getBaseUrl() + outerImg.subSequence(outerImg.indexOf("webapps") + 7, outerImg.length()));
        jsonInfo.put("inner", wechat.getBaseUrl() + innerImg.subSequence(innerImg.indexOf("webapps") + 7, innerImg.length()));
        jsonInfo.put("openid", openid);
        HashMap<String, String> map = MapUtil.toHashMap(jsonInfo);
        logger.info("map===" + map.toString());
        try {
            applyService.save(map);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

}
